'use strict';

const BaseController = require('./base.js');
const fs = require('fs');
class SettingController extends BaseController {
  async index() {
    let result = await this.ctx.model.Setting.findAll();    
    await this.ctx.render("admin/setting/index", {
        list: result[0]
    })

  }
  async doEdit() {
    const { ctx } = this;
    const body = ctx.request.body;
    const file = ctx.request.files[0];

    
    //获取要修改的数据
    let settingObj = await this.ctx.model.Setting.findByPk(body.id);
    if (!settingObj) {
        await this.error("非法请求", `/${this.config.adminPath}/setting`);
        return;
    }

    if (file) {
        var source = fs.createReadStream(file.filepath);
        var filename = this.ctx.service.tools.getCosUploadFile(file.filename);
        //异步 改成 同步
        await this.ctx.service.tools.uploadCos(filename, source);
        await settingObj.update({
            ...body,
            siteLogo:filename,
        });
    } else {
        await settingObj.update(body);
    }    
    await this.success("修改系统设置成功",`/${this.config.adminPath}/setting`);
  }
}

module.exports = SettingController;
